package com.yyn.client2.dao;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

@Service
public class ClientDao {
    public void client(String name) throws IOException {
//        创通道
        SocketChannel socketChannel = SocketChannel.open();
//        非阻塞
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
//        让该通道绑定一下需要连接的ip（本地的）
        boolean connect = socketChannel.connect(new InetSocketAddress("127.0.0.1", 9003));
        socketChannel.register(selector, SelectionKey.OP_CONNECT);//请求连接后监听读事件   收消息

//        由于一个selector对应一个客户端
//        这里的轮询其实只有一个
        while (true) {
            selector.select();//进行轮询
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
//                轮询 发现是连接请求操作
                if (key.isConnectable()) {//判断是否连接操作的通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    if (channel.isConnectionPending()) {//判断是否正在连接
                        channel.finishConnect();//连接成功  才是真正的连接  把该绑定的发到远程请求
                        channel.configureBlocking(false);
                        send send = new send(socketChannel, name, "叶泳相");
                        send.start();//让线程启动起来
                        System.out.println("客户端 已经连上服务端");
//      new一个线程去专门发送消息

                        send.start();//让线程启动起来
                    }
                } else if (key.isReadable()) {//读 （服务端返回的数据）
                    SocketChannel channel = (SocketChannel) key.channel();
                    receive(channel);
                }
                iterator.remove();//轮询完一遍就删了  防止阻碍了下次轮询找匹配的操作
            }

        }

    }

    public void receive(SocketChannel channel) throws IOException {
        channel.configureBlocking(false);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int len = 0;
        while ((len = channel.read(buffer)) > 0) {//如果读取完了返回-1
            buffer.flip();
            SocketAddress localAddress = channel.getLocalAddress();
            System.out.println("客户端：" + localAddress.toString() + "发送：" + new String(buffer.array(), 0, len));
        }
    }


}

 class send extends Thread {
    private SocketChannel socketChannel;
    private String name, toSocketChanner;

    public send(SocketChannel socketChannel, String name, String toSocketChanner) {
        this.socketChannel = socketChannel;
        this.name = name;
        this.toSocketChanner = toSocketChanner;
    }

    @Override
    public void run() {
//        进行写
        Scanner scanner = new Scanner(System.in);
        System.out.println("写出要发送的消息：");
        String text = scanner.next();
        String message = name + ":" + text;
        try {
//            写数据 要UTF8  put乱码
            socketChannel.write(ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
